<?php

namespace app\admin\controller\tcfence;

use app\common\controller\Backend;
use GuzzleHttp\Client;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 围栏管理
 *
 * @icon fa fa-circle-o
 */
class Fence extends Backend
{
    
    /**
     * Fence模型对象
     * @var \app\admin\model\tcfence\Fence
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\tcfence\Fence;

        $tcconfig=get_addon_config('tcfence');
        if(!$tcconfig['tencentkey']){
            $this->error('请配置腾讯地图key再测试插件功能，如已配置key，清除缓存重新访问即可');
        }
        $this->assign('tcconfig',$tcconfig);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['areamanage'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    //https://ask.fastadmin.net/article/2527.html

    /**
     * @return mixed
     * 地图视图
     */
    public function map()
    {
        return $this->view->fetch();
    }


    /**
     * @return \think\response\Json
     * 获取地址信息-用于腾讯地图查询位置
     */
    public function get_location()
    {
        $address = $this->request->param('address');
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' . $address . '&key='.get_addon_config('tcfence')['tencentkey'];
        $client = new Client();
        $ret = $client->get($url)->getBody()->getContents();
        return json($ret);
    }


    /**
     * 添加
     */
    public function add()
    {
        $areamanage_id = $this->request->param('areamanage_id');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (isset($areamanage_id)) {
                    $params['areamanage_id'] = $areamanage_id;
                }

                if (!$params['name']){
                    $this->error('围栏名称不能为空');
                }

                $fence_data = '';
                if (isset($params['datas'])) {
                    if (!$params['datas']) {
                        $this->error('围栏信息不能为空');
                    } else {
                        $fence_data = $params['datas'];
                        unset($params['datas']);
                    }
                } else {
                    $this->error('围栏信息不能为空');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);


                    /*TODO 新增围栏数据逻辑START*/
                    $id = $this->model->id;
                    if ($fence_data) {
                        $fence_data_list = json_decode($fence_data, true);
                        foreach ($fence_data_list as $k => $v) {
                            $int = array();
                            $int['paths'] = json_encode($v['paths']);
                            $int['fence_id'] = $id;
                            $int['fencedataid'] = $v['id'];

                            $checkfencedata = \app\admin\model\tcfence\Fencedata::where(['fencedataid' => $v['id']])->find();
                            if ($checkfencedata) {
                                $checkfencedata->paths = json_encode($v['paths']);
                                $checkfencedata->save();
                            } else {
                                $fencedata = new \app\admin\model\tcfence\Fencedata();
                                $fencedata->data($int);
                                $fencedata->save();
                            }

                        }
                    } else {
                        $this->error('围栏信息不能为空');
                    }
                    /*TODO 新增围栏数据逻辑END*/

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $isshow = 1;
        if (isset($areamanage_id)) {
            $isshow = 2;
        }
        $this->assign('isshow', $isshow);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            $fence_data = '';
            if (isset($params['datas'])) {
                if ($params['datas']) {
                    $fence_data = $params['datas'];
                    unset($params['datas']);
                }
            } else {
                $this->error('围栏信息不能为空2');
            }



            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    /*TODO 更新围栏数据逻辑START*/
                    if ($fence_data) {
                        $fence_data_list = json_decode($fence_data, true);
                        foreach ($fence_data_list as $k => $v) {
                            $int = array();
                            $int['paths'] = json_encode($v['paths']);
                            $int['fence_id'] = $ids;
                            $int['fencedataid'] = $v['id'];

                            $checkfencedata = \app\admin\model\tcfence\Fencedata::where(['fence_id' => $ids])->find();

                            if ($checkfencedata) {
                                $checkfencedata->paths = json_encode($v['paths']);
                                $checkfencedata->fencedataid =  $v['id'];
                                $checkfencedata->save();
                            }
                        }
                    }
                    /*TODO 更新围栏数据逻辑END*/
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $pence_list = \app\admin\model\tcfence\Fencedata::where(['fence_id' => $ids])->select();
        $this->view->assign("pence_list", $pence_list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
